<?php

namespace App\Jobs;

use App\Models\User;
use App\Service\Redis\RedisBaseService;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class UserLearnQuestionCountOfTodayRankJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Execute the job.
     *
     * @param RedisBaseService $redisBaseService
     * @return void
     * @throws \RedisException
     */
    public function handle(RedisBaseService $redisBaseService)
    {
        /**
         * 今日刷题数
         */
        // 获取到所有的今日刷题数
        $allRows = [];

        // 查数据库
        $userForAll = \Illuminate\Support\Facades\DB::table('qh_user_learn_question_logs')
            ->selectRaw('userId, COUNT(*) as count')
            ->whereBetween('created_at', [Carbon::now()->startOfDay(), Carbon::now()->endOfDay()])
            ->groupBy('userId')
            ->orderByDesc('count')
            ->limit(15)
            ->pluck('userId', 'count')
            ->toArray();
        foreach ($userForAll as $count => $userId) {
            if (array_key_exists('userId='.$userId, $allRows)) continue;
            $allRows['userId='.$userId] = $count;
        }

        // 根据值对数组进行降序排序，保持索引关联
        arsort($allRows);

        // 创建新数组来存储键和值
        $userIds = [];
        foreach ($allRows as $key => $value) {
            $userIds[] = explode('=', $key)[1];
        }
        $userIds = array_slice($userIds, 0, 15);

        $todayList = DB::table('user')->select([
            'id',
            'avatar',
            'nickname',
            'learnQuestionCount',
            'learnQuestionCountOfToday',
            'correctQuestionCount',
            'wrongQuestionCount',
            'correctQuestionCountOfToday',
            'wrongQuestionCountOfToday'
        ])
            ->whereIn('id', $userIds)
            ->whereBetween('learnQuestionOfLastTime', [now()->startOfDay(), now()->endOfDay()])
            ->get()->sortByDesc(function ($user) use ($userIds, $redisBaseService, $allRows) {
            //$user->learnQuestionCount = $redisBaseService->getUserLearnQuestionCount($user->id);
            // $user->learnQuestionCountOfToday = intval($allRows['userId='.$user->id]);
            //$user->learnQuestionCountOfToday = $redisBaseService->getUserLearnQuestionCountOfToday($user->id);
            //$user->questionRateOfToday = $redisBaseService->getUserQuestionRateOfToday($user->id);
            //$user->questionRate = $redisBaseService->getUserQuestionRate($user->id);
            //return $allRows['userId='.$user->id];
            //$user->learnQuestionCountOfToday = $redisBaseService->getUserLearnQuestionCountOfToday($user->id);
            $sum = $user->correctQuestionCountOfToday + $user->wrongQuestionCountOfToday;
            $user->questionRateOfToday = ($sum > 0 && $user->correctQuestionCountOfToday > 0) ? round($user->correctQuestionCountOfToday / $sum, 2) : 0;;
            return $user->learnQuestionCountOfToday;
        })->values()->toArray();

        // 存入缓存
        \Cache::put('rank:userLearnQuestionOfTodayCountRank', serialize($todayList), 1800);
        Log::debug('[JOB]-userLearnQuestionOfTodayCountRank:DONE', $todayList);
    }
}
